from Selenium2Library.keywords.keywordgroup import KeywordGroup
from Selenium2Library.locators import ElementFinder
import time

class _BreezeTransferKeywords(KeywordGroup):
    """Library for Breeze Transfer Keywords purposes.
    
    This library is used in Breeze projects.
    """
    def __init__(self):
        """Does nothing. init only"""
        print '_BreezeTransferKeywords.__init__'
                    
            
    def select_to_account(self, to_account, account_list_xpath):  
        ''' Return selected to account name and number by given account name.
        '''
        toAccountInfo = self._get_own_account_information(to_account, account_list_xpath)
        if toAccountInfo['hasAccount'] == True:
            toAccountInfo['accountLink'].click()

        return toAccountInfo['accountName']+'\n'+toAccountInfo['accountNumber']

    def select_from_account_pk(self, index):
        ''' Return a list of selected account name and account info by given currency.
        '''
        
        from_acct_xpath = "//div[@class='list-view']/dl/dd/ul/*"
        from_list = self._element_find(from_acct_xpath, False, False)
        from_acct_list = []
        i = 1
        
        for acct in from_list:
            account_name = acct.find_element_by_class_name("info-primary")
            account_number = acct.find_element_by_class_name("info-secondary")
            
            if i == int(index):
                # self._info("found %s %s" % (currency_cd, temp_currency))
                from_acct_info = (account_name.text + '\n' + account_number.text)
                # self._info("from_acct_info")
                # self._info(from_acct_info)
                from_acct_list.append(from_acct_info)
                from_acct_list.append(account_name.text)
                from_acct_list.append(account_number.text)
                acct.click()
                break
            else:
                i+=1
                
        return from_acct_list
		
		
    def loop_login(self, users):
        ''' Return a list of selected account name and account info by given currency.
        '''
        
        user_xpath = "//input[@name='j_username']"
	password ="//input[@name='j_password']"
	login_btn ="//input[@name='Login']"
	logout_btn ="//input[@name='Logout']"
        users_list = users.split(',')
	self._info(len(users_list))
	user_info =[]
        
        
        for user in users_list:
            self.wait_until_page_contains_element(user_xpath)
	    self.wait_until_page_contains_element(password)
	    self.input_text(user_xpath,user)
	    self.input_text(password,"iscm1357")
            self.click_element(login_btn)
	    time.sleep(2)
	    self._info((user))
	    user_info.append(user)
	    logout_element = self._element_find(logout_btn, False, False)
	    if logout_element:
		user_info.append("1")
		self.click_link("Overview")
		time.sleep(1)
		rows = self._element_find("//table[@class='tbl_listing']/tbody/tr[@class='tbl_listing_row_even' or @class='tbl_listing_row_odd']", False, False)
                self._info(len(rows))
		user_info.append(len(rows))
		self.click_element(logout_btn)
		time.sleep(1)
		self.click_link('link=Login again')
	    else:
		user_info.append("0")
                
        return user_info
    
    def select_to_account_pk(self, index, txn_type):
        ''' Return selected account info by given currency.
        '''
        to_acct_xpath = "//div[@id='main']/div[@id='content']/div/dl/*"
        amount_p = 'info-amount s-positive'
        amount_n = 'info-amount s-negative'
        acctName_cn = 'info-primary'
        acctNum_cn = 'info-secondary'
        acctNum_scb ='info-third'
        to_acct_info = []
        temp_list = ''
        account_number = ''
        
        #self._synchronize()
        self._info("BEGIN")
        elements = self._element_find(to_acct_xpath, False, False)
        self._info(elements)
        if txn_type == "OAT":
            temp_list = self._find_OAT_list(elements)

        if txn_type == "CARD":
            temp_list = self._find_CARD_list(elements)
            
        if txn_type == "SCB":
            temp_list = self._find_OtherAccount_list(elements)

        if txn_type == "BP":
            temp_list = self._find_Biller_list(elements)

        if txn_type == "VP":
            temp_list = self._find_Voucher_list(elements)
            
        i = 1
        self._info(temp_list)
        for acct in temp_list:
            self._info(index)
            account_link = acct.find_element_by_class_name(acctName_cn).text
            self._info(account_link)
            if txn_type == "SCB" or txn_type == "BP":
                account_number =  acct.find_element_by_class_name(acctNum_scb).text   
            else:
                if txn_type != "VP":
                    account_number = acct.find_element_by_class_name(acctNum_cn).text
                    self._info(account_number)

            if i == int(index):
                self._info("fined")
                to_acct_info.append(account_link + '\n' + account_number)
                to_acct_info.append(account_number)
                to_acct_info.append(account_link)
                acct.click()
                break
            else:
                i+=1
            
        return to_acct_info


        
    def _find_OAT_list(self, acct_list):
        flag = False
        acct_xpath = "//dd/ul/*"

        for element in acct_list:
            if flag == False:
                temp = element.find_element_by_id("OAT")
            if temp != None:
                if "My Accounts" == temp.text:
                    flag = True
                    temp = None
                    continue    
            if flag == True:
                oat_list = element.find_elements_by_xpath(acct_xpath)
                break
        
        return oat_list

    def _find_CARD_list(self, acct_list):
        flag = False
        acct_xpath = "//dd/ul/*"

        for element in acct_list:
            if flag == False:
                self._info("begin find card List")
                temp = element.find_element_by_xpath("//div[@id='main']/div[@id='content']/div/dl/dt[@id='CCP']")
                self._info(temp)
            if temp != None:
                if "My Cards" == temp.text:
                    flag = True
                    temp = None
                    continue    
            if flag == True:
                oat_list = element.find_elements_by_xpath(acct_xpath)
                self._info(oat_list)                                    
                break
        
        return oat_list

    def _find_OtherAccount_list(self, acct_list):
        flag = False
        acct_xpath = "//dd/ul/*"

        for element in acct_list:
            if flag == False:
                self._info("begin find SCB List")
                temp = element.find_element_by_xpath("//div[@id='main']/div[@id='content']/div/dl/dt[@id='IBFT']")
                self._info(temp)
            if temp != None:
                if "Other Accounts" == temp.text:
                    flag = True
                    temp = None
                    continue    
            if flag == True:
                oat_list = element.find_elements_by_xpath(acct_xpath)
                self._info(oat_list)                                    
                break
        
        return oat_list
    
    def _find_Biller_list(self, acct_list):
        flag = False
        acct_xpath = "//dd/ul/*"

        for element in acct_list:
            if flag == False:
                self._info("begin find Biller List")
                temp = element.find_element_by_xpath("//div[@id='main']/div[@id='content']/div/dl/dt[@id='BP']")
                self._info(temp)
            if temp != None:
                if "My Bills" == temp.text:
                    flag = True
                    temp = None
                    continue    
            if flag == True:
                oat_list = element.find_elements_by_xpath(acct_xpath)
                self._info(oat_list)                                    
                break
        
        return oat_list

    def _find_Voucher_list(self, acct_list):
        flag = False
        acct_xpath = "//dd/ul/*"

        for element in acct_list:
            if flag == False:
                self._info("begin find voucher List")
                temp = element.find_element_by_xpath("//div[@id='main']/div[@id='content']/div/dl/dt[@id='MVP']")
                self._info(temp)
            if temp != None:
                if "Prepaid Voucher Purchase" == temp.text:
                    flag = True
                    temp = None
                    continue    
            if flag == True:
                oat_list = element.find_elements_by_xpath(acct_xpath)
                self._info(oat_list)                                    
                break
        
        return oat_list
    def get_to_account_balance(self, to_account, account_list_xpath):
        ''' Return selected to account balance by given account name. Must be used before select_to_account()
        '''
        toAccountInfo = self._get_own_account_information(to_account, account_list_xpath)
        return toAccountInfo['balance']
    
    def select_from_account(self, from_account, account_list_xpath):
        ''' Return selected from account name and number by given account name.
        '''
        fromAccountInfo = self._get_own_account_information(from_account, account_list_xpath)
        if fromAccountInfo['hasAccount'] == True:
            fromAccountInfo['accountLink'].click()

        return fromAccountInfo['accountName']+'\n'+fromAccountInfo['accountNumber']

    def get_from_account_name(self, from_account, account_list_xpath):
        ''' Return selected from account name by given account name. Must be used before select_from_account()
        '''
        fromAccountInfo = self._get_own_account_information(from_account, account_list_xpath)
        return fromAccountInfo['accountName']
    
    def get_from_account_balance(self, from_account, account_list_xpath):
        ''' Return selected from account balance by given account name. Must be used before select_from_account()
        '''
        fromAccountInfo = self._get_own_account_information(from_account, account_list_xpath)
        return fromAccountInfo['balance']
    def get_from_account_balance_PK(self, from_account_number, account_list):

        for i in xrange(len(account_list)):
            self._info("get account balance")
            self._info(i)
            self._info(account_list[i][1])
            self._info(from_account_number)
            if account_list[i][1] ==  from_account_number:
                self._info(account_list[i][3])
                return account_list[i][3]
        
    def _get_own_account_information(self, account_selected, account_list_xpath):
        ''' Return to account information by given account name.
        '''
        accountList = self._element_find(account_list_xpath, False, False)
        accountInfo = {'accountLink':'','accountName':'','accountNumber':'','balance':'','hasAccount':False}
        for account in accountList:
            accountName = account.find_element_by_class_name('info-primary').text
            accountNumber = account.find_element_by_class_name('info-secondary').text
            balance = account.find_element_by_class_name('info-amount').text
            if account_selected in accountName.strip():
                self._info("found %s %s %s" % (accountName, accountNumber, balance))
                accountInfo['accountLink'] = account
                accountInfo['accountName'] = accountName
                accountInfo['accountNumber'] = accountNumber
                accountInfo['balance'] = balance
                accountInfo['hasAccount'] = True
                break
        
        return accountInfo

    
    def _synchronize(self, sync_ui=True, sync_ws=True, nodelay=False):
        """Wait until page is ready, i.e. application finished rendering and webservice requests are completed
        """
        self._debug("Entering to synchronize")
        if not nodelay:
            time.sleep(3)
        maxtries = 60
        while maxtries:
            maxtries -= 1
            UIisRendering, WSinProgress = self.execute_javascript(" try { return [ BreezeUIisRendering, BreezeWSinProgress ]; } catch (e) { return [ true, false ] } ")
            ui_ok = (not UIisRendering) if sync_ui else True
            ws_ok = (not WSinProgress) if sync_ws else True
            if ui_ok and ws_ok:
                self._debug("Leaving synchronize with %d tries left" % maxtries)
                return
            time.sleep(1.0)
        self._debug("Leaving synchronize by timeout")
        
    def get_transfer_Amount_Biller(self):
        ''' Used in make-transfer.tsv to get transafer date.
        '''
        transfer_amount_list =[]
        transfer_amount_xpath = "//*[@id='amt']"
        browser = self._current_browser()
        transfer_amount = browser.find_element_by_xpath(transfer_amount_xpath).text
        self._info(transfer_amount)
        transfer_amount_list.append(transfer_amount)
        if len(transfer_amount)>6:
            if len(transfer_amount)==7:
                transfer_amount = transfer_amount[:1] + ',' + transfer_amount[1:]
            else:    
                transfer_amount = transfer_amount[:2] + ',' + transfer_amount[2:]
        self._info(transfer_amount)
        transfer_amount_list.append(transfer_amount)
        return transfer_amount_list
    
    def get_transfer_date(self):
        ''' Used in make-transfer.tsv to get transafer date.
        '''
        return self._run('get_transfer_date')
            
    def _get_transfer_date_pk(self):
        date_list = []
        transfer_date_xpath = "//*[@id='TR_DT']"
        browser = self._current_browser()
        transfer_date = browser.find_element_by_xpath(transfer_date_xpath)
        date_temp = []

        date = transfer_date.text
        self._info(date)
        date = date.replace("Choose the date\n","")
        self._info(date)
        date_temp = date.split(',')
        date_list.append(date)
        self._info(len(date_temp))
        self._info(date_temp[0])
        date_list.append(date_temp[1].strip())
        
        return date_list

    def _get_transfer_date_hk(self):
        date_list = []
        transfer_date_xpath = "//*[@id='TR_DT']"
        browser = self._current_browser()
        transfer_date = browser.find_element_by_xpath(transfer_date_xpath)
        date_temp = []

        date = transfer_date.text
        self._info(date)
        date = date.split("\n")[1]
        self._info(date)
        date_temp = date.split(',')
        date_list.append(date)
        date_list.append(date_temp[1].strip())
        
        return date_list
    
    def _get_transfer_date_id(self):
        date_list = []
        transfer_date_xpath = "//*[@id='TR_DT']"
        browser = self._current_browser()
        transfer_date = browser.find_element_by_xpath(transfer_date_xpath)
        date_temp = []

        date = transfer_date.text
        self._info(date)
        date_temp = date.split(',')
        date_list.append(date)
        date_list.append(date_temp[1].strip())
        
        return date_list
    
    def _find_lastest_transaction_history(self):
        transfer_history_xpath = "//div[@class='list-view']/dl/*"
        browser = self._current_browser()
        history_list = self._element_finder.find(browser, transfer_history_xpath)
        today_flag = False
        result_his = history_list[0]

        for his in history_list:
            today_history = his.find_element_by_class_name("info-primary")
            today_his = today_history.text
            self._info("history text:" + today_his)
                
            if today_his == 'Today':
                today_flag = True
                continue

            if today_flag == True:
                self._info("find break here and end this function")
                result_his = his
                break

        return result_his
    
    def _find_today_specified_transaction_history(self, transfer_type, account_name, amount_value):
        self._info(transfer_type)
        self._info(account_name)
        self._info(amount_value)
        transfer_history_xpath = "//div[@class='list-view']/dl/*"
        browser = self._current_browser()
        history_list = self._element_finder.find(browser, transfer_history_xpath)
        today_flag = False
        result_his = history_list[0]
        
        for his in history_list:
            today_history = his.find_element_by_class_name("info-primary")
            today_his = today_history.text
            self._info("history text:" + today_his)
                
            if today_his == 'Today':
                today_flag = True
                continue
            
            if today_his == 'Yesterday':
                today_flag = False
                self._info("Not Found the specified record in today's transfer history.")
                break

            if today_flag == True:
                type = his.find_element_by_class_name("info-primary").text.strip()
                name = his.find_element_by_class_name("info-secondary").text.strip()
                value = his.find_element_by_class_name("info-amount").text.strip()
                diff_value = self.get_transfer_amount(value, amount_value)
                if type==transfer_type and name==account_name and diff_value=='0.0' :
                    self._info("Find break here and end this function")
                    result_his = his
                    break

        return result_his

    def get_from_account_transfer_history(self, transfer_type, account_name, amount_value):
        ''' Used in make-transfer.tsv to get tfrom account transfer history.
        
        In keyword of Verify Transfer History
        '''
        today_his_list = []
        #today_his = self._find_lastest_transaction_history()
        today_his = self._find_today_specified_transaction_history(transfer_type, account_name, amount_value)
        from_acct = today_his.find_element_by_class_name("info-secondary").text
        self._info(from_acct)
        today_his_list.append(from_acct)
        today_amount = today_his.find_element_by_class_name("info-amount").text
        self._info(today_amount)
        today_his_list.append(today_amount)
        return today_his_list

    def get_from_account_transfer_history_by_name(self,from_account_name,from_amount,txn_type):
        ''' Used in make-transfer.tsv to get tfrom account transfer history.
                In keyword of focus Account Name and Amount
        '''
        transfer_history_xpath = "//div[@class='list-view']/dl/*"
        browser = self._current_browser()
        history_list = self._element_finder.find(browser, transfer_history_xpath)
        today_flag = False
        exist_flag = False
        result_his = history_list[0]
        current_list=[]
        TXN_TYPE_HIS =""
        
        if txn_type == "OAT":
           TXN_TYPE_HIS = 'Between Own Accounts'
           
        if txn_type == "CARD":
           TXN_TYPE_HIS = 'Card Payment'
           
        if txn_type == "SCB":
           TXN_TYPE_HIS = 'Local Transfer (Within the Bank)'
           
        if txn_type == "IBFT":
           TXN_TYPE_HIS = 'Local Transfer (Outside the Bank)'
           
        for his in history_list:
            today_history = his.find_element_by_class_name("info-primary")
            today_his = today_history.text
            self._info("history text:" + today_his)
                
            if today_his == 'Today':
                today_flag = True
                continue
            if today_his == 'Yesterday':
                today_flag = False
                break
            if today_flag == True and today_his == TXN_TYPE_HIS:
                self._info("find !!! and continue this function")
                current_list.append(his)
                continue

            
        for his in current_list:
            current_from_account = his.find_element_by_class_name("info-secondary")
            current_account = current_from_account.text
            self._info("current ACCOUNT:" + current_account)
            self._info("FROM ACCOUNT:" + from_account_name)
            current_amount = his.find_element_by_class_name("info-amount").text
            self._info("current AMOUNT:" + current_amount)
            self._info("FROM AMOUNT:" +'PKR'+from_amount)
            if current_account == from_account_name and current_amount=='PKR'+from_amount:
                self._info("FINED")
                exist_flag = True
                transfer_type = his.find_element_by_class_name("info-primary")
                transfer_type.click()
                return exist_flag
            
        return exist_flag

    def get_from_account_schedule_txn_history_by_time(self,from_account_name,from_amount,txn_type,schedule_time):
        ''' Used in make-transfer.tsv to get tfrom account transfer history.
                In keyword of focus Account Name and Amount
        '''
        #transfer_history_xpath = "//div[@class='list-view']/dl/dt/dd[starts-with(@id,'"+schedule_time+"')]"
        transfer_history_xpath = "//dd[starts-with(@id,'"+schedule_time+"')]"
        self._info("xpath:" + transfer_history_xpath)
        browser = self._current_browser()
        history_list = self._element_finder.find(browser, transfer_history_xpath)
        self._info(len(history_list))
        today_flag = False
        exist_flag = False
        result_his = history_list[0]
        current_list=[]
        TXN_TYPE_HIS =""
        
        if txn_type == "OAT":
           TXN_TYPE_HIS = 'Between Own Accounts'
           
        if txn_type == "CARD":
           TXN_TYPE_HIS = 'Card Payment'
           
        if txn_type == "SCB":
           TXN_TYPE_HIS = 'Local Transfer (Within the Bank)'
           
        if txn_type == "IBFT":
           TXN_TYPE_HIS = 'Local Transfer (Outside the Bank)'
           
        if txn_type == "BP":
           TXN_TYPE_HIS = 'Bill Payment'
        if txn_type == "VP":
           TXN_TYPE_HIS = 'Prepaid Voucher Purchase'
            
        for his in history_list:
            current_from_account = his.find_element_by_class_name("info-secondary")
            current_account = current_from_account.text
            self._info("current ACCOUNT:" + current_account)
            self._info("FROM ACCOUNT:" + from_account_name)
            current_amount = his.find_element_by_class_name("info-amount").text
            self._info("current AMOUNT:" + current_amount)
            self._info("FROM AMOUNT:" +'PKR'+from_amount)
            transfer_type = his.find_element_by_class_name("info-primary")
            self._info("transfer_type"+transfer_type.text)
            self._info(TXN_TYPE_HIS)
            if current_account == from_account_name and current_amount=='PKR'+from_amount:
                if transfer_type.text == TXN_TYPE_HIS:
                    self._info("FINED")
                    exist_flag = True
                    time.sleep(3)
                    transfer_type.click()
                    return exist_flag
            
        return exist_flag
        
    def click_current_transfer_history(self, transfer_type, account_name, amount_value):
        ''' Used in make-transfer.tsv to get current transfered transaction history.
        
        In keyword of Verify Transfer History Detail
        '''
        #today_his = self._find_lastest_transaction_history()
        today_his = self._find_today_specified_transaction_history(transfer_type, account_name, amount_value)
        transfer_type = today_his.find_element_by_class_name("info-primary")
        transfer_type.click()

    def click_current_transfer_history_by_name(self,from_account_name,from_amount):
        ''' Used in make-transfer.tsv to get current transfered transaction history.
        
        In keyword of Verify Transfer History Detail
        '''
        transfer_history_xpath = "//div[@class='list-view']/dl/*"
        browser = self._current_browser()
        history_list = self._element_finder.find(browser, transfer_history_xpath)
        today_flag = False
        exist_flag = False
        result_his = history_list[0]
        current_list=[]
        for his in history_list:
            today_history = his.find_element_by_class_name("info-primary")
            today_his = today_history.text
            self._info("history text:" + today_his)
                
            if today_his == 'Today':
                today_flag = True
                continue
            if today_his == 'Yesterday':
                today_flag = False
                break
            if today_flag == True and today_his=='Between Own Accounts':
                self._info("find break here and end this function")
                current_list.append(his)
                continue

            
        for his in current_list:
            current_from_account = his.find_element_by_class_name("info-secondary")
            current_account = current_from_account.text
            self._info("current:" + current_account)
            current_amount = his.find_element_by_class_name("info-amount").text
            self._info("current_amount:" + current_amount)    
            if current_account == from_account_name:
                exist_flag = True
                today_his_but=his
                break
        transfer_type = today_his_but.find_element_by_class_name("info-primary")
        transfer_type.click()

    def select_to_others_account(self, bankname):
        ''' Return selected account info by given bankname.
        '''
        element = self._element_find("//*[@id='IBFT']/a", True, False)
        element.click()
        self.wait_until_page_contains_element("//dt[@id='IBFT']/following-sibling::dd/ul/li")

        other_acct_xpath = "//dt[@id='IBFT']/following-sibling::dd/ul/li"
        ibft_list = self._element_find(other_acct_xpath, False, False)

        to_acct_info = ''
        for acct in ibft_list:
            account = acct.find_element_by_xpath("./a/span[1]")
            temp_bankname = acct.find_element_by_xpath("./a/span[2]")
            acct_number = acct.find_element_by_xpath("./a/span[3]")

            if bankname in temp_bankname.text.strip():
                self._info("found %s %s" % (bankname, temp_bankname.text))
                to_acct_info = (account.text + '\n' + acct_number.text)
                acct.click()
                break

        return to_acct_info

    def get_transfer_amount(self,stringA,stringB):
        ''' Return two strings minus number
            By Carl
        ''' 
        a=''
        b=''
        if len(stringA)>16 or len(stringB)>16:
			stringA = stringA[-16:]
			stringB = stringB[-16:]
		
        for i in stringA:
            if ord(i)>=46 and ord(i)<=57:
                a=a+i
                
        for i in stringB:
            if ord(i)>=46 and ord(i)<=57:
                b=b+i
        
        result=round(float(a)-float(b),2)
        
        
        return str(result)
